package cn.dlc.com.config;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @author 邓立川
 * @date 2021/1/7 14:22
 * @desc 局部过滤器，继承AbstractGatewayFilterFactory，指定参数，
 * 其他的局部过滤器都是这么实现的，可以查看源码
 */
@Component
public class LogGatewayFilterFactory extends AbstractGatewayFilterFactory<LogGatewayFilterFactory.Config> {

    public LogGatewayFilterFactory(){
        super(LogGatewayFilterFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("consoleLog","cacheLog");
    }

    @Override
    public GatewayFilter apply(LogGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

                System.out.println("-----------------");

                if(config.isCacheLog()) {
                    System.out.println("cache日志开启...");
                }
                if(config.isConsoleLog()) {
                    System.out.println("consoleLog开启...");
                }

                return chain.filter(exchange);
            }
        };
    }

    public static class Config{

        private Boolean consoleLog;
        private Boolean cacheLog;

        public Boolean isConsoleLog() {
            return consoleLog;
        }

        public void setConsoleLog(Boolean consoleLog) {
            this.consoleLog = consoleLog;
        }

        public Boolean isCacheLog() {
            return cacheLog;
        }

        public void setCacheLog(Boolean cacheLog) {
            this.cacheLog = cacheLog;
        }
    }
}
